<template>
  <div id="add_role_app">
    <el-dialog
      :title="formdata.id ? '编辑角色' : '新增角色'"
      :visible.sync="isShow.flag"
      width="50%"
    >
      <el-form ref="form" :model="formdata" label-width="80px" :rules="rules">
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="formdata.rolename"></el-input>
        </el-form-item>
        <el-form-item label="角色权限">
          <el-tree
            :default-checked-keys="tree_list"
            :data="menuList"
            show-checkbox
            node-key="id"
            :default-expanded-keys="[2, 3]"
            :props="defaultProps"
            ref="tree_ref"
          >
          </el-tree>
        </el-form-item>

        <el-form-item label="角色状态" prop="status">
          <el-radio-group v-model="formdata.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow.flag = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
export default {
  created() {
    this.menuListActions();
  },
  computed: {
    ...mapState("menu_model", ["menuList"]),
  },
  methods: {
    setTree() {
      console.log(this.$refs.tree_ref);
    },
    setData(obj) {
      //设置表单的数据
      this.formdata = { ...obj };
      this.tree_list = obj.menus.split(",");
    },
    submit() {
      // 判断是更新还是新增
      var url = "";
      if (this.formdata.id) {
        //更新
        url = "/roleedit";
      } else {
        //新增
        url = "/roleadd";
      }
      //整理数据结构
      this.formdata.menus = this.$refs.tree_ref.getCheckedKeys().join(",");
      //发起请求
      this.$axios.post(url, this.formdata).then((res) => {
        console.log(res);
      });
      //重置表单
      this.formdata = {
        rolename: "",
        menus: "",
        status: "",
      };
      this.$refs.tree_ref.setCheckedKeys([]);
      //关闭模态框
      this.isShow.flag = false;
      //从新请求数据
      this.$emit("reload");
    },
    ...mapActions("menu_model", ["menuListActions"]),
  },
  props: ["isShow"],
  data() {
    return {
      tree_list: [],
      formdata: {
        rolename: "",
        menus: "",
        status: "",
      },
      defaultProps: {
        children: "children",
        label: "title",
      },
      rules: {
        rolename: {
          required: true,
          message: "角色名称不可以为空",
          trigger: "blur",
        },
        status: {
          required: true,
          message: "角色状态不可以为空",
          trigger: "blur",
        },
      },
    };
  },
};
</script>

<style>
</style>
